//index.js
//获取应用实例
const http = require("../../utils/util.js");
var Crypto = require('../../utils/cryptojs/cryptojs.js').Crypto;
const app = getApp();
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var tempFilePath;
Page({
  data: {
    houBaoStyle:1,
    userInfo:[],
    shuoming1:'小伙伴们说对口令就能获得随即打赏',
    shuoming2:'好友听完你说的话就能领取赏金',
    shuoming3:'好友念出你的答案就能领取赏金',
    kouling:'', 
    Money:'',
    Number:'',
    answer:'',
    // 录音动画；
    isSpeaking: false,
    speakerUrl: '../image/speaker0.png',
    speakerUrlPrefix: '../image/speaker',
    speakerUrlSuffix: '.png',

    voiceResult:false,
  },
  //事件处理函数
  ChangeTab:function(e){
    var that = this;
    
    var currentTab = e.currentTarget.dataset.id;
    console.log(currentTab)
    that.setData({
      houBaoStyle: currentTab,
    })
  },
  onLoad: function () {
    var that = this;
    wx.getUserInfo({
      success:function(user){
        console.log(user)
        that.setData({
          userInfo:user.userInfo,
        })
      }
    })
    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log("获取token APP")
        console.log(res.data);
        var token = res.data;
        if (token == ''|| token == undefined) {
          app.login();
        }

      },
      fail: function (res) {
        console.log("获取toekn 失败")
        console.log(res)
        app.login();
      }
    })
   console.log(app.netWorkData.isreq);
  },
// 口令红白生成
  // 获取语音
  startVoice: function () {
    var that = this;
    // console.log("开始录音");
    // this.setData({
    //   isSpeaking: true,
    // })
    // that.speaking();
    // wx.startRecord({
    //   success: function (res) {
    //     console.log("录音结束")
    //     var tempFilePath = res.tempFilePath;
      
    //     var result = app.receiveVoice(tempFilePath);
    //     console.log(result)
    //   },
    //   fail: function () {

    //   }
    // })
    console.log("开始录音")
    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  // 测试语音播放结果；
  play: function () {
    console.log("zhixi")
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },


  endstartVoice: function () {
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
      that.uploadVoice();
    })
  },

  // 跳转链接

  tomyRecord:function(){
    var that = this;
    wx.navigateTo({
      url: './mRecord/myRecord',
    })

  },
  toShare:function(){
    var that = this;
    // 正式：
    switch (that.data.houBaoStyle){
      case "1":
        that.iskouling();
      case "2":
        that.isqingting();

    }
  },
  iskouling:function(){
    if (that.data.kouling == '') {
      app.showInfo("请设置口令");
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.perpay();
    }
  },
  isqingting:function(){
    var that = this;
    console.log("执行倾听")
    if (!that.data.voiceResult){
      app.showInfo("请重新上传语音")
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.perpay();
    }

  },
  perpay:function(){
    var that = this;
    var url = app.globalData.localApi +"/redpack/prepay";
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var token = res.data;
        var timestamp = app.timestamp()
        wx.request({
          url: url,
          method: "POST",
          data: {
            timestamp:timestamp,
            token: token,
            sign: Crypto.MD5(app.sign(url,token,timestamp)),
            packText:that.data.kouling,
            packMoney:parseInt(that.data.Money),
            packCount:parseInt(that.data.Number),
          },
          success:function(res){
            console.log(res)
          }
        })
      },
    })
 
  },
  // 上传语音：
  uploadVoice:function(){
    var that = this;
    console.log("程序进入上传语音");
    var tempFilePath = that.tempFilePath
    console.log(tempFilePath);
    wx.getStorage({
      key: 'token',
      success: function(res) {
        that.setData({
          token:res.data,
        })
      },
    })
    const url = app.globalData.localApi + "/redpack/receiveVoice";
    console.log("上传语音url"+ url);
    console.log("上传语音filePath"+ tempFilePath);

    wx.uploadFile({
      url: url,
      filePath: tempFilePath,
      name: "file",
      formData: {
        'user': 'test'
      },
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        console.log("请求成功")
        console.log(res)
        that.setData({
          voiceResult: true,
        })
      },
      fail: function (res) {
        console.log(res)
        console.log("上传失败")
        app.showInfo("网络开小差了,语音没有上传成功")
        that.setData({
          voiceResult: false,
        })
      }
    })
  },

  // 上传图片
  uploadPic:function(){
    var that  = this;
    wx.chooseImage({
      success: function(res) {
        console.log(res);
        console.log(res.tempFiles[0].path)
        wx.uploadFile({
          url: app.globalData.localApi + '/redpack/receiveVoice',
          filePath: res.tempFiles[0].path,
          name: "image",
          formData: {
            shuoming:"测试上传图片"
          },
          success: function (res) {
            console.log(res.code);
            console.log("11111111111111111111111111111111111")

          },
          fail:function(res){
            console.log(res)
          }
        })
      },
    })
  },
  // 获取页面填入的值
  koulingInput:function(e){
    var that = this;
    console.log(e.detail.value)
      that.setData({
        kouling: e.detail.value,
      }) 
  },
  koulingInput1: function (e) {
    var that = this;
    console.log(e.detail.value)
    var conf = app.checkChinese(e.detail.value);
    console.log(conf);
    if (conf) {
      that.setData({
        kouling: e.detail.value,
      })

    } else {
      app.showInfo("请输入中文口令")

    }

  },
  MoneyInput:function(e){
    var that = this;
    console.log(e.detail.value)
    that.setData({
      Money: e.detail.value,
    })
  },
  NumberInput: function (e) {
    var that = this;
    console.log(e.detail.value)
    that.setData({
      Number: e.detail.value,
    })
  },
  jubenAnswerInput:function(e){
    var that = this;
    console.log(e.detail.value);
    that.setData({
      answer:e.detail.value,
    })
  },
  // 麦克风帧动画 
  speaking: function () {
    //话筒帧动画 
    var that = this;
    var i = 0;
    that.speakerInterval = setInterval(function () {
      i++;
      i = i % 7;
      that.setData({
        speakerUrl: that.data.speakerUrlPrefix + i + that.data.speakerUrlSuffix,
      });
      console.log("[Console log]:Speaker image changing...");
    }, 300);
  }
})
